package com.weichen.studentgameexchange.message.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.weichen.studentgameexchange.common.common.Result;
import com.weichen.studentgameexchange.common.common.StrIsNumOrChinese;
import com.weichen.studentgameexchange.common.exception.ServiceException;
import com.weichen.studentgameexchange.message.entity.Message;
import com.weichen.studentgameexchange.message.dao.MessageMapper;
import com.weichen.studentgameexchange.message.entity.MessageRelated;
import com.weichen.studentgameexchange.message.entity.MessageType;
import com.weichen.studentgameexchange.message.entity.vo.MessageVo;
import com.weichen.studentgameexchange.message.service.IMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 惟尘
 * @since 2025-02-08
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    @Autowired
    MessageMapper messageMapper;

    /**
     * 分页查询
     * @param keyword
     * @param page
     * @param size
     * @return
     */
    @Override
    public Result adminPage(String keyword, Integer page, Integer size) {
        Page<Message> messagePage = new Page<>(page,size);
        LambdaQueryWrapper<Message> messageLambdaQueryWrapper = new LambdaQueryWrapper<>();
        messageLambdaQueryWrapper.orderByDesc(Message::getMessageId);
        if (!StrUtil.isBlankIfStr(keyword)){
            Object o = StrIsNumOrChinese.strIsNumOrChinese(keyword);
            if (o instanceof Long)
                messageLambdaQueryWrapper.eq(Message::getMessageId,o);
            else if (o instanceof Result)
                throw new ServiceException("搜索输入的关键字不正确！");
            List<Long> typeIds = Db.lambdaQuery(MessageType.class)
                    .like(MessageType::getTypeName, o)
                    .list()
                    .stream()
                    .map(MessageType::getTypeId)
                    .toList();
            typeIds.forEach(typeId ->{
                messageLambdaQueryWrapper.eq(Message::getTypeId,typeId);
            });
        }
        Page<Message> selectPage = messageMapper.selectPage(messagePage, messageLambdaQueryWrapper);
        List<Message> records = selectPage.getRecords();
        List<MessageVo> vos = records.stream().map(message -> {
            MessageVo vo = BeanUtil.copyProperties(message, MessageVo.class);
            if (vo.getRelatedId() != null) {
                MessageRelated related = Db.lambdaQuery(MessageRelated.class)
                        .eq(MessageRelated::getRelatedId, vo.getRelatedId())
                        .one();
                vo.setCommentId(related.getCommentId());
                vo.setGameId(related.getGameId());
                vo.setStrategyId(related.getStrategyId());
                vo.setActivityId(vo.getActivityId());
            }
            MessageType type = Db.lambdaQuery(MessageType.class)
                    .eq(MessageType::getTypeId, vo.getTypeId())
                    .one();
            if (StrUtil.isBlankIfStr(type))
                vo.setTypeName("没有对应的消息类型名！");
            vo.setTypeName(type.getTypeName());
            return vo;
        }).toList();
        Page<MessageVo> messageVoPage = new Page<>();
        messageVoPage.setCurrent(messagePage.getCurrent());
        messageVoPage.setSize(messagePage.getSize());
        messageVoPage.setTotal(messagePage.getTotal());
        messageVoPage.setRecords(vos);
        return Result.success(messageVoPage);
    }

    /**
     * 新增消息
     * @param messageVo
     * @return
     */
    @Override
    public Result adminAdd(MessageVo messageVo) {
        //1.获取relatedId
        Long gameId = messageVo.getGameId();
        Long commentId = messageVo.getCommentId();
        Long strategyId = messageVo.getStrategyId();
        Long activityId = messageVo.getActivityId();
        MessageRelated related = new MessageRelated();
        boolean b = false;
        if (!StrUtil.isBlankIfStr(gameId)){
            related.setGameId(gameId);
            b = true;
        }
        else if (!StrUtil.isBlankIfStr(commentId)){
            related.setCommentId(commentId);
            b = true;
        }
        else if (!StrUtil.isBlankIfStr(strategyId)){
            related.setStrategyId(strategyId);
            b = true;
        }
        else if (!StrUtil.isBlankIfStr(activityId)){
            related.setActivityId(activityId);
            b = true;
        }
        if (b){
            Db.save(related);
            Long relatedId = related.getRelatedId();
            messageVo.setRelatedId(relatedId);
        }
        //2.获取typeId
        String typeName = messageVo.getTypeName();
        MessageType type = Db.lambdaQuery(MessageType.class)
                .eq(MessageType::getTypeName, typeName)
                .one();
        if (StrUtil.isBlankIfStr(type))
            return Result.error("消息类型不能为空！");
        messageVo.setTypeId(type.getTypeId());
        //3.复制给message对象
        Message message = BeanUtil.copyProperties(messageVo, Message.class);
        messageMapper.insert(message);
        return Result.success(message);
    }

    /**
     * 删除单个消息
     * @param messageId
     * @return
     */
    @Override
    public Result adminDeleteOne(Long messageId) {
        Long relatedId = Db.lambdaQuery(Message.class)
                .eq(Message::getMessageId, messageId)
                .one()
                .getRelatedId();
        if (!StrUtil.isBlankIfStr(relatedId))
            Db.lambdaUpdate(MessageRelated.class)
                    .eq(MessageRelated::getRelatedId,relatedId)
                    .remove();
        messageMapper.deleteById(messageId);
        return Result.success();
    }
}
